package javacmd;

import java.io.*;
import java.util.Scanner;

/**
 * Created by User on 2018/1/5.
 */
public class CmdUtil {

    public static Process exec(String command) {
        try {
            Process process = Runtime.getRuntime().exec(command);
            InputStream inputStream = process.getInputStream();
            InputStream errorStream = process.getErrorStream();
            CmdStreamUtil.print(inputStream);
            CmdStreamUtil.print(errorStream);
//            OutputStream outputStream = process.getOutputStream();
//            CmdStreamUtil.write(outputStream);
            return process;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    static class CmdStreamUtil {

        // 打印信息
        public static Thread print(InputStream inputStream) throws IOException {
            PrintThread printThread = new PrintThread(inputStream);
            printThread.start();
            return printThread;
        }

        public static Thread write(OutputStream outputStream) throws IOException {
            WriteThread writeThread = new WriteThread(outputStream);
            writeThread.start();
            return writeThread;
        }

        static class WriteThread extends Thread {

            private OutputStream outputStream;

            public WriteThread(OutputStream outputStream) {
                this.outputStream = outputStream;
            }

            @Override
            public void run() {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))){
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.out.println("打印" + line);
                        outputStream.write((line).getBytes());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        static class PrintThread extends Thread {

            private InputStream inputStream;

            public PrintThread(InputStream inputStream) {
                this.inputStream = inputStream;
            }

            @Override
            public void run() {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))){
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.out.println(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
